package chances.epg.navigator.history;

import java.util.Iterator;
import java.util.LinkedList;

public class NavigateHistory implements java.io.Serializable {

	private static final long serialVersionUID = 730385014066224277L;

	private String name;
	private String formURL;

	public final static String ACCESS_HISTORY_NAME = "historyQueue";
	public final static String EXTERNAL_BACKURL = "backUrl";

	private LinkedList<HistoryEntry> history = new LinkedList<HistoryEntry>();

	public NavigateHistory(final String entry) {
		this.formURL = entry;
	}

	public HistoryEntry peek() {
		return history.getLast();
	}

	public boolean isEmpty() {
		return this.size() == 0;
	}

	public String getLastPath() {
		if (!this.isEmpty()) {
			HistoryEntry aEntry = history.getLast();
			return aEntry.getURL();
		} else {
			return null;
		}
	}

	public HistoryEntry get(int idx) {
		if (idx > -1 && idx < this.history.size()) {
			return this.history.get(idx);
		} else {
			return null;
		}
	}

	public void add(HistoryEntry entry) {

		int count = history.size();
		int idx = -1;
		for (int i = 0; i < count; i++) {
			HistoryEntry aEntry = history.get(i);
			if (entry.getPath().equals(aEntry.getPath())) {
				idx = i;
				break;
			}
		}
		if (idx > -1) {
			idx = history.size() - idx;
			for (int i = 0; i < idx; i++) {
				this.history.pollLast();
			}
		}
		// this.addExternalUrl(request);
		//
		// entry = NavigateHistoryFactory.createHistoryEntry(request);
		this.history.add(entry);
	}

	public Iterator<HistoryEntry> iterator() {
		return this.history.iterator();
	}

	public void clear() {
		this.history.clear();
	}

	public int size() {
		return this.history.size();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int indexOf(final String path) {
		try {
			for (int i = 0; i < this.history.size(); i++) {
				HistoryEntry historyEntry = this.history.get(i);
				if (path.equals(historyEntry.getPath())) {
					return i;
				}
			}
		} catch (java.lang.Throwable e) {
			
		}
		return -1;

	}

	public String getFormURL() {
		return formURL;
	}

	public void pop(int idx) {
		int value = this.size() - idx;
		for (int i = 0; i < value; i++) {
			this.history.pollLast();
		}
	}

}
